import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Start {
	
	String pathLavoro = new String();
	private String DBHost = "localhost:3306";
	private String nomeDB = "dbcinema";       
	private String nomeUtente = "root";   
	private String pwdUtente = "noemi2002";           
	private Statement stmt = null;
	private ResultSet resultSet = null;
	
	Vector<FilmStory> film = new Vector<FilmStory>();

	public static void main(String args[]){
		Start st = new Start();
		
		// il metodo main ha un argomento obbligatorio: directory di lavoro.
		if(args.length==0 || args[0].equals("-help")){
			System.out.println(" PARAMETRO OBBLIGATORIO : ");
			System.out.println("[path lavoro]");
			System.exit(0);
		}
		st.pathLavoro = args[0];	
		st.createStoryFile();

	}	

	private void createStoryFile(){
		// connessione al db 
		Connection con = getConnection(DBHost, nomeDB, nomeUtente, pwdUtente);

		// query: recupero le coppie titolo-trama dei film presenti nel db
		try {
			stmt = con.createStatement();
			String query = "select f.titolo, f.trama from film f;";
			resultSet = stmt.executeQuery(query);	

		// inserimento dei film nel vettore film
			while (resultSet.next()) {
				FilmStory fs = new FilmStory();
				fs.setTitle(resultSet.getString("titolo"));
				fs.setStory(resultSet.getString("trama"));
				film.add(fs);
			}
			
			resultSet.close();
			stmt.close();
			con.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}

		// scorrimento del vettore e costruzione del file in utf-8
		writeSgml();
	}
	
	// connessione al db
	private Connection getConnection(String dbHost, String dbName, String user, String psw) {
		Connection con = null;  
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://"+dbHost+"/" + dbName + "?user=" + user + "&password=" + psw);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}
	
	/**
	 * Scrittura del file.sgml con struttura di ogni elemento:
	 * <DOC>
	 * <DOCNO> titolo </DOCNO>
	 * <TITLE> titolo </TITLE>
	 * <TEXT> trama film </TEXT>
	 * </DOC>
	 */
	public void writeSgml(){
		
		StringBuffer doc = new StringBuffer();
		String document = null; 	
		
		String id = "";
		Pattern re = null;
		Matcher m = null;
		String docno = "";
		
		for (int i = 0; i < film.size(); i++) {
			FilmStory elemento = film.elementAt(i);
			id = elemento.getTitle();
			re = Pattern.compile(" ");
			m = re.matcher(id);
			docno = m.replaceAll("_");
			document = "<DOC>\r\n<DOCNO>"+docno+
					   "</DOCNO>\r\n<TITLE>"+elemento.getTitle()+
					   "</TITLE>\r\n<TEXT>"+elemento.getStory()+
					   "</TEXT>\r\n</DOC>\r\n";
			doc.append(document);
		}
		writeUtf8(doc.toString(), pathLavoro+"/story.sgml");
	}
				
	// scrittura su file in utf-8.
	public void writeUtf8(String str, String outputPath) {
		try {
				FileOutputStream fos = new FileOutputStream(outputPath);
				OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
				PrintWriter out = new PrintWriter(osw);
				System.out.println("Scrittura file : " + outputPath+ " con codifica : " + osw.getEncoding());
				out.write(str);
				out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

}// end class

